package com.cskaoyan.market.controller;

import com.cskaoyan.market.db.domain.MarketCart;
import com.cskaoyan.market.db.domain.MarketUser;
import com.cskaoyan.market.service.WxCartService_YYH;
import com.cskaoyan.market.util.ResponseUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Author: 鲸落
 * @Date: 2024/05/21/20:10
 * @Version: 1.0
 * @Description:
 */
@RestController
@RequestMapping("wx/cart")
public class WxCartController_YYH {
    @Autowired
    SecurityManager securityManager;
    @Autowired
    WxCartService_YYH wxCartService;

    @GetMapping("goodscount")   // 购物车中商品数量 功能正常
    public Object goodscount() {
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();
        int data = 0;
        if(user == null){
            return ResponseUtil.ok(data);
        }
        // 调用Service层方法
        List<MarketCart> carts = wxCartService.goodscount(user);
        for (MarketCart cart : carts) {
            data = data+cart.getNumber();
        }
        return ResponseUtil.ok(data);
    }
    @PostMapping("add")     // 添加商品到购物车 功能正常
    public Object add(@RequestBody Map map){
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser) subject.getPrincipal();  // 获取当前登录用户信息
        // 如果当前用户没有登陆，则需要先登录
        if(user == null){
            return ResponseUtil.fail(501,"请登录");
        }
        Integer goodsId = (Integer) map.get("goodsId");
        Integer number = (Integer) map.get("number");   // 需要添加的商品数量
        Integer productId = (Integer) map.get("productId");
        // 调用Service层方法 data为添加成功后返回的购物车中商品数量
        Integer data = wxCartService.add(goodsId,number,productId,user);
        return ResponseUtil.ok(data);
    }
}
